package com.shuqi.activity.viewport;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ProgressBar;

import com.shuqi.controller.R;

/**
 * webkit进度条
 * 
 * @author linyuren
 * 
 */
public class WebKitProgressBar extends ProgressBar {

    private Drawable topDrawable;
    private Drawable bottomDrawable;
    private float topDrawableScale = 111f / 13;
    private float topDrawableOffset = 81f / 111;

    public WebKitProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray mArray =
                context.obtainStyledAttributes(attrs, R.styleable.webkit_progressbar, 0, 0);
        topDrawable = mArray.getDrawable(R.styleable.webkit_progressbar_topDrawable);
        bottomDrawable = mArray.getDrawable(R.styleable.webkit_progressbar_bottomDrawable);
        mArray.recycle();
    }

    public WebKitProgressBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (topDrawable != null && bottomDrawable != null) {
            final int height = bottom - top;
            topDrawable.setBounds(0, 0, (int) topDrawableScale * height, height);
            bottomDrawable.setBounds(0, 0, right - left, height - getPaddingTop()
                    - getPaddingBottom());
        }
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        final int mWidth = getWidth();

        // 绘制底层灰色图片
        if (mWidth > 0 && bottomDrawable != null) {
            canvas.save();
            canvas.translate(getPaddingLeft(), getPaddingTop());
            bottomDrawable.draw(canvas);
            canvas.restore();
        }

        // 绘制进度条
        super.onDraw(canvas);

        // 绘制光晕效果
        if (mWidth > 0 && topDrawable != null) {
            // 计算top图片位置
            final float scale = getProgress() * 1.0f / getMax();
            // 修正图片位置,以为topdrawable有透明区域
            final int curLeft =
                    (int) (mWidth * scale - topDrawableOffset * topDrawable.getBounds().right);//
            canvas.save();
            canvas.translate(curLeft, 0);
            topDrawable.draw(canvas);
            canvas.restore();
        }
    }

    @Override
    public void invalidateDrawable(Drawable dr) {
        invalidate();
    }

}
